import {shopAddCartAPI,shopDelCartAPI,shopCartAPI}from'../services/shopCart'
import {defineStore } from 'pinia'
import { ref,computed } from 'vue'
export const useCart = defineStore('cart',()=> {
   const carts=ref([]);//购物车数据  

  //  加入购物车
  const addToCart= async (productId,amount="1",price='')=>{
  await  shopAddCartAPI({
    product:productId,//商品id
    amount , //    根据传递的数量正负，会自动的计算最新的数量
    price
    })
    loadData()
  }
  // 删除商品
  const delToCart=async(id)=>{
    await shopDelCartAPI(id)
    loadData()
  }
  // 获取购物车数据
  const loadData=async()=>{
     const  res=await shopCartAPI()
     carts.value=res.data.filter((item) => item.product)
         .map((item) => ({ ...item, checked: false }))
  }
  // 获取商品数量
   const cartCount=computed(()=>carts.value.reduce((pre,cur)=>pre+cur.amount,0))
  /**
   * 重置购物车数据
   */
   const resetCart = () => {
    carts.value = []};
    return{
      cartCount, carts,addToCart,delToCart,loadData,resetCart
    }
}) 